package com.yf.course.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.course.modules.course.entity.CourseFileUnlock;
import com.yf.course.modules.course.mapper.CourseFileUnlockMapper;
import com.yf.course.modules.course.service.CourseFileUnlockService;
import com.yf.course.modules.course.service.CourseRefFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* <p>
* 课件解锁业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2022-04-26 17:34
*/
@Service
public class CourseFileUnlockServiceImpl extends ServiceImpl<CourseFileUnlockMapper, CourseFileUnlock> implements CourseFileUnlockService {


    @Autowired
    private CourseRefFileService courseRefFileService;

    @Override
    public String unlockFile(String userId, String courseId, Integer sort) {

        // 排序错误
        if(sort==null){
            return null;
        }

        // 解锁下一个
        String nextId = courseRefFileService.findNextFile(courseId, sort);

        QueryWrapper<CourseFileUnlock> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CourseFileUnlock::getUserId, userId)
                .eq(CourseFileUnlock::getCourseId, courseId)
                .eq(CourseFileUnlock::getFileId, nextId);

        // 已解锁无需操作
        int count = this.count(wrapper);
        if(count > 0){
            return nextId;
        }

        // 添加解锁信息
        CourseFileUnlock lock = new CourseFileUnlock();
        lock.setFileId(nextId);
        lock.setCourseId(courseId);
        lock.setUserId(userId);
        // 解锁时间
        lock.setCreateTime(new Date());
        this.save(lock);

        return nextId;
    }
}
